import { defineStore } from 'pinia'
import { piniaStore } from '@/store'
import api from '@/api'

import { ElMessage } from 'element-plus'

import { useRouteStore } from './route'
import { useMenuStore } from './menu'

import menuConfig from '../../util/menu'

export const useUserStore = defineStore(
    // 唯一ID
    'user',
    {
        state: () => ({
            account: localStorage.account || '',
            token: localStorage.token || '',
            failure_time: localStorage.failure_time || '',
            permissions: [],
            list: localStorage.list ? JSON.parse(localStorage.list) : [],
            menuList: localStorage.menuList ? JSON.parse(localStorage.menuList) : [],
        }),
        getters: {
            isLogin: state => {
                let retn = false
                if (state.token) {
                    if (new Date().getTime() < Number.parseInt(state.failure_time) + 86400000) {
                        retn = true
                    }
                }
                return retn
            },
            menu: state => {
                state.menuList = [{"component":"Layout","id":78,"key":"SYS_1","level":1,"list":[{"component":"Layout","id":80,"key":"SYS_MENU","level":2,"list":[{"component":"Layout","id":82,"key":"SYS_MENU_LIST","level":3,"name":"菜单列表","parentId":80,"path":"/menuList","sort":1}],"name":"菜单管理","parentId":78,"path":"test/page2","permission":"mgr:menu:edit","sort":1},{"component":"Layout","id":81,"key":"SYS_USER","level":2,"list":[{"component":"Layout","id":84,"key":"1","level":3,"name":"部门管理","parentId":81,"path":"path","permission":"1","sort":1},{"component":"Layout","id":85,"key":"1","level":3,"name":"部门管理","parentId":81,"path":"path","permission":"1","sort":1},{"component":"Layout","icon":"test-icon11","id":88,"key":"test-111","level":3,"name":"测试11","parentId":81,"path":"/test111","permission":"test-per11","redirect":"/href111","sort":23}],"name":"用户管理","parentId":78,"path":"test/page3","permission":"mgr:user:edit","sort":2}],"name":"系统管理2","parentId":0,"path":"222","sort":1},{"component":"Layout","id":87,"key":"111","level":1,"list":[],"name":"其他信息","parentId":0,"path":"、","permission":"、","sort":1},{"component":"Layout","id":79,"key":"EAM_1","level":1,"list":[],"name":"设备管理","parentId":0,"path":"test/page1","sort":2}]
                const listRoute = state.list.map(mes => {
                    const dic = [
                        '',
                        'finance',
                        'operate',
                        'production',
                        'delivery',
                        'receive',
                        'repairs',
                        'repairAndAccept',
                        'recovery',

                    ]
                    return {
                        path: dic[mes.id],
                        name: dic[mes.id],
                        component: () => import('@/views/system/staff/page2/page2-1.vue'),
                        meta: {
                            title: mes.name + '管理'
                        },
                    }
                })

                const cfg = menuConfig(listRoute)
                // 78 系统管理 79 设备管理 80 菜单管理  81 人员管理 86 设备信息 87 其他信息
                const transFn = i => {
                    let res = {}
                    console.log(i)
                    res = cfg[i.id]
                    if(!res) return
                    if(i.list) {
                        for(let j of i.list) {
                            const tmp = transFn(j)
                            if(tmp) {
                                res.children.push(tmp)
                            }
                        }

                    }
                    return res
                }



                return state.menuList.map(mes => {
                    return transFn(mes)
                }).filter(i => i !== void(0))
            }
        },
        actions: {
            login(data) {
                return new Promise((resolve, reject) => {
                    // 通过 mock 进行登录
                    api.post('api/mgr/login',
					{
                        account: data.account,
                        pwd: data.password
                    }
					, {
						// baseURL: '/mock/'
					}).then(res => {

                        if(res.c === 0) {
                            localStorage.setItem('account', res.d.account)
                            localStorage.setItem('token', res.d.token)
                            localStorage.setItem('failure_time', new Date().getTime())

                            this.account = res.d.account
                            this.token = res.d.token
                            this.failure_time = new Date().getTime()

                            this.loadList().then(() => {
                                console.log(1)
                                ElMessage({
                                    type: 'success',
                                    message: '登陆成功'
                                })
                                window.location.reload()
                                resolve()
                            })

                        } else {
                            ElMessage({
                                type: 'error',
                                message: res.m
                            })

                            resolve()
                        }

                    }).catch(error => {
                        reject(error)
                    })
                })
            },

            loadList() {

                return new Promise((resolve) => {
                    Promise.all([new Promise((resolve) => {
                        api.post('api/mgr/deptList', {})
                        .then(res => {
                            localStorage.setItem('list', JSON.stringify([...res.d.records]))
                            this.list = JSON.stringify([...res.d.records])
                            resolve()
                        })
                    }), new Promise((resolve) => {
                        api.post('api/mgr/userMenuList', {"clientId": "1"})
                        .then(res => {
                            localStorage.setItem('menuList', JSON.stringify([...res.d]))
                            this.menuList = JSON.stringify([...res.d])
                            resolve()
                        })
                    })]).then(() => {console.log('load'); resolve()})
                })


            },

            logout() {
                return new Promise(resolve => {
                    api.post('api/mgr/logout', )
					    .then(res => {


						})
                    const routeStore = useRouteStore()
                    const menuStore = useMenuStore()
                    // localStorage.removeItem('account')
                    // localStorage.removeItem('token')
                    // localStorage.removeItem('failure_time')
                    localStorage.clear()
                    this.account = ''
                    this.token = ''
                    this.failure_time = ''
                    this.loadList()
                    routeStore.removeRoutes()
                    menuStore.setActived(0)
                    resolve()
                })
            },
            // 获取我的权限
            getPermissions() {
                return new Promise(resolve => {
                    // 通过 mock 获取权限
                    api.get('member/permission', {
                        baseURL: '/mock/',
                        params: {
                            account: this.account
                        }
                    }).then(res => {
                        this.permissions = res.data.permissions
                        resolve(res.data.permissions)
                    })
                })
            },
            editPassword(data) {
                return new Promise(resolve => {
                    api.post('api/member/edit/password', {
                        account: this.account,
                        password: data.password,
                        newpassword: data.newpassword
                    }, {
                        baseURL: '/mock/'
                    }).then(() => {
                        resolve()
                    })
                })
            }
        }
    }
)

export function useUserOutsideStore() {
    return useUserStore(piniaStore)
}
